﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using System.Threading;

namespace XMM.Dialoges.Library
{
    /// <summary>
    /// Interaktionslogik für AddTVShow.xaml
    /// </summary>
    public partial class AddTVShow : Window
    {
        Controls.Library.Import_Episode ParentEpisodeImporter { get; set; }

        public bool PendingChanges
        {
            get
            {
                return _PendingChanges;
            }
        }

        private bool _PendingChanges = false;

        public AddTVShow(Controls.Library.Import_Episode ctlParentEpisodeImporter)
        {
            InitializeComponent();

            ParentEpisodeImporter = ctlParentEpisodeImporter;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            LoadGenres();
        }

        private void LoadGenres()
        {
            cmbGenre.IsEnabled = false;
            cmbGenre.Items.Clear();

            List<Objects.Genre> lGenres = Objects.Genre.getAllGenres();

            if (lGenres != null && lGenres.Count > 0)
            {
                foreach (Objects.Genre oGenre in lGenres)
                {
                    cmbGenre.Items.Add(oGenre);
                }
            }

            cmbGenre.IsEnabled = true;
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (txtTitle.Text != String.Empty)
            {
                if (Objects.Series.CheckExistance(txtTitle.Text) == false)
                {
                    Objects.Series oShow = new Objects.Series();
                    oShow.Name = txtTitle.Text;
                    oShow.Director = txtDirector.Text;
                    oShow.Cast = ctlCast.Cast;
                    oShow.Plot = ctlPlot.Plot;
                    if (cmbGenre.SelectedIndex > -1)
                    {
                        Objects.Genre oSelectedGenre = (Objects.Genre)cmbGenre.SelectedItem;
                        oShow.GenreID = oSelectedGenre.GenreID;
                    }
                    if (oOnlineDetails != null && oOnlineDetails.Id != 0)
                    {
                        oShow.TvdbID = oOnlineDetails.Id;
                    }

                    if (oShow.SaveNew())
                    {
                        // Get Series-ID.
                        oShow = Objects.Series.getLatestSeries();

                        // Save CoverArt if any.
                        if (ctlCoverArt.HasCover)
                        {
                            SaveCoverArt(oShow.SeriesID);
                        }

                        // Ask user to auto-import seasons from tvdb.
                        AskImportSeasons(oShow.SeriesID);

                        ParentEpisodeImporter.reloadShows(oShow);
                        Close();
                    }
                }
                else
                {
                    MessageBox.Show("Der eingegebene Serientitel wird bereits verwendet!", "Serie bereits vorhanden", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
            }
            else
            {
                MessageBox.Show("Bitte geben Sie zumindest den Titel ein!", "Kein Titel - Keine Eingabe...", MessageBoxButton.OK, MessageBoxImage.Exclamation);
            }

        }

        private void AskImportSeasons(int iSeriesID)
        {
            if (MessageBox.Show("Möchten Sie Informationen für existierende Staffeln automatisch importieren?", "Staffeln automatisch importieren?", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                int i = 1;
                for (i = 1; i <= oOnlineDetails.NumSeasons; i++)
                {
                    Objects.SeriesSeason oSeason = new Objects.SeriesSeason();
                    oSeason.SeriesID = iSeriesID;
                    oSeason.Number = i;
                    oSeason.SaveNew();
                }
                MessageBox.Show((i - 1).ToString() + " Staffeln wurden erstellt!", "Staffeln importiert", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void SaveCoverArt(int iSeriesID)
        {
            // Check if CoverArt-Image exists.
            if (System.IO.File.Exists(ctlCoverArt.CoverImagePath))
            {
                // Get Settings-Object
                Settings oSettings = new Settings();

                // Set Target Path for large Image
                // [FileLibraryPath] + movies\\xmm_[PrimaryFileName].jpg
                string sTargetImagePath = oSettings.LibraryDataStorage + "series\\images\\xmm_" + iSeriesID.ToString() + ".jpg";

                // Set Target Path for thumbnail image.
                string sTargetThumbnailPath = oSettings.LibraryDataStorage + "series\\thumb\\xmm_" + iSeriesID.ToString() + ".jpg";

                // Create new files
                try
                {
                    if (File.Exists(sTargetImagePath))
                        File.Delete(sTargetImagePath);
                    if (File.Exists(sTargetThumbnailPath))
                        File.Delete(sTargetThumbnailPath);

                    // Copy large version
                    File.Copy(ctlCoverArt.CoverImagePath, sTargetImagePath);

                    // Create thumbnail
                    System.Drawing.Bitmap bmpLargeImage = new System.Drawing.Bitmap(ctlCoverArt.CoverImagePath);
                    System.Drawing.Bitmap bmpThumbnail = Functions.Imaging.ResizeBitmap(bmpLargeImage, (int)(bmpLargeImage.Width / 10), (int)(bmpLargeImage.Height / 10));

                    FileStream fsOutput = System.IO.File.Create(sTargetThumbnailPath);
                    bmpThumbnail.Save(fsOutput, System.Drawing.Imaging.ImageFormat.Jpeg);
                    fsOutput.Flush();
                    fsOutput.Close();
                    fsOutput.Dispose();
                }
                catch (IOException ex)
                {
                    System.Windows.MessageBox.Show("Fehler beim Speichern der Bilder für \"" + txtTitle.Text + "\": " + ex.Message + Environment.NewLine + Environment.NewLine + "Die Serie wird ohne CoverArt importiert.", "Fehler in CoverArt", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            if (PendingChanges | ctlPlot.Plot != String.Empty | ctlCast.Cast != String.Empty)
            {
                if (MessageBox.Show("Ihre Eingaben werden verworfen! Möchten Sie wirklich abbrechen?", "Wirklich abbrechen", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No)
                {
                    return;
                }
            }

            Close();
        }

        private void txtTitle_TextChanged(object sender, TextChangedEventArgs e)
        {
            _PendingChanges = true;
        }

        private void txtDirector_TextChanged(object sender, TextChangedEventArgs e)
        {
            _PendingChanges = true;
        }

        private void cmbGenre_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            _PendingChanges = true;
        }

        private TvdbLib.Data.TvdbSeries oOnlineDetails;

        private void btnTvDBSearch_Click(object sender, RoutedEventArgs e)
        {
            Settings oSettings = new Settings();
            Dialoges.WebData.TVDBSearch dlgTVDBSearch = new WebData.TVDBSearch(txtTitle.Text);
            if ((bool)dlgTVDBSearch.ShowDialog())
            {
                //processSearchResult(oSettings, dlgTVDBSearch);
                ParameterizedThreadStart tsProcessResult = new ParameterizedThreadStart(processSearchResult);
                Thread thProcessResult = new Thread(tsProcessResult);
                thProcessResult.Start(new object[] { dlgTVDBSearch.SelectedResult });
            }
        }

        private void processSearchResult(object Data)
        {
            Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Lade Serien-Details...", true });
            Settings oSettings = new Settings();

            object[] oaData = (object[])Data;
            tvdbInterface.SearchResult oSelectedResult = (tvdbInterface.SearchResult)oaData[0];

            //tvdbInterface.SearchResult oSelectedResult = dlgTVDBSearch.SelectedResult;

            if (oSelectedResult != null)
            {
                TvdbLib.Data.TvdbSeries oSeriesDetails = tvdbInterface.tvdbInterface.downloadShowInfo(oSettings.LibraryDataStorage + @"\tvdb\cache\", oSelectedResult.TvdbID, "GER");
                if (oSeriesDetails != null)
                {
                    //updateGUI();
                    Dispatcher.Invoke(new updateGUICallback(updateGUI), new object[] { oSeriesDetails });
                }
            }

            Dispatcher.Invoke(new setStatusCallback(setStatus), new object[] { "Bereit...", false });
        }

        private void updateGUI(TvdbLib.Data.TvdbSeries oSeriesDetails)
        {
            Settings oSettings = new Settings();

            txtTitle.Text = oSeriesDetails.SeriesName;
            string sActors = oSeriesDetails.ActorsString.Replace("|", ", ");
            ctlCast.setCast(sActors);
            ctlPlot.setPlot(oSeriesDetails.Overview);

            // Show Banner-Art-Selection.
            oSeriesDetails.SeriesBanners[0].LoadBanner();
            string sCacheFileName = "img_graphical_" + oSeriesDetails.SeriesBanners[0].BannerPath.Split('/')[1];
            string sCacheFilePath = oSettings.LibraryDataStorage + @"tvdb\cache\" + oSeriesDetails.Id.ToString() + @"\" + sCacheFileName;
            ctlCoverArt.setCoverImage(sCacheFilePath);

            txtTitle.FontStyle = System.Windows.FontStyles.Italic;

            oOnlineDetails = oSeriesDetails;
        }

        private delegate void updateGUICallback(TvdbLib.Data.TvdbSeries oSeriesDetails);

        public void setStatus(string sNewMessage, bool bEnableMarquee)
        {
            pbStatus.IsIndeterminate = bEnableMarquee;
            lblStatus.Content = sNewMessage;
        }

        public delegate void setStatusCallback(string sNewMessage, bool bEnableMarquee);
    }
}
